<template>
  <basic-dialog
    title="已有商品价格组"
    width="60%"
    :visible="dialogVisible"
    :handleClose="handleCloseShowDialog"
  >
    <el-form ref="formData" :model="formData" label-width="80px" inline>
      <el-form-item label="SPU编码" prop="spuNo">
        <el-input
          v-model="formData.spuNo"
          placeholder="请输入SPU编码"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="formData.productName"
          placeholder="请输入商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleQueryData"
          >查询</el-button
        >
        <el-button
          @click="handleResetData"
          >清空</el-button
        >
      </el-form-item>
    </el-form>
    <el-tabs
      v-model="tabs.current"
      @tab-click="handleSwitchTabs"
    >
      <el-tab-pane
        label="未关联"
        :name="tabs.nameList[0]"
      >
      </el-tab-pane>
      <el-tab-pane
        label="已关联"
        :name="tabs.nameList[1]"
      >
      </el-tab-pane>
    </el-tabs>
    <SkusTable
      showActionCol
      showPagination
      :tableHeight="400"
      :actionColWidth="60"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.dataSource"
      :pagination="pagination"
      :total="pagination.total"
      :pageSizes="pageSizes"
      :actionRender="renderActionBtnFunc"
      @pageChange="handlePageChange"
      @pageSizeSelect="handlePageSizeChange"
    />
    <el-row type="flex" justify="center" slot="ft">
      <el-button @click="handleCloseShowDialog">取消关联</el-button>
      <el-button
        type="primary"
        v-preventReClick
        @click="handleSubmitPriceGroup"
      >确定关联</el-button
      >
    </el-row>
  </basic-dialog>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import BasicDialog from '@/components/BasicDialog';
import SkusTable from '@/components/skusTable';
import { isResponseSuccess, generateUuid } from '@/utils/bizUtils';
export default {
  components: { BasicDialog, SkusTable },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    /* 当前页面name名称，必要props */
    pageNameType: {
      type: String,
      required: true
    },
    columns: {
      type: Array,
      default () {
        return [
          {
            title: '商品名称',
            key: 'productName',
          },
          {
            title: 'SPU编码',
            key: 'spuNo',
          },
          {
            title: '品类',
            key: 'categoryPath',
          },
          {
            title: '品牌',
            key: 'brandName',
          }
        ]
      }
    },
    /* 商品的productUuid（商品新增、待准入-未完善页面有用到 */
    productUuid: {
      type: String
    },
    /* 是否是多计量（商品新增、待准入-未完善页面有用到 */
    isSaleMultiUnit: {
      type: String
    },
    /* 当前页面关联的uuid的key名称，默认是uuid */
    uuidName: {
      type: String,
      default: 'uuid'
    },
    pageSizeOpts: {
      type: Array,
      default () {
        return [10, 20, 50, 100];
      }
    },
  },
  data () {
    return {
      dialogVisible: false,
      formData: {
        spuNo: '',
        productName: ''
      },
      tabs: {
        current: 'notAssociated', // 当前tabs页签
        nameList: ['notAssociated', 'isAssociated'] // tabs页签key集合
      },
      tableInfo: {
        columns: this.columns,
        dataSource: []
      },
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页条数
        total: 0 // 总条数
      },
      pageSizes: this.pageSizeOpts,
      selectionList: [],
      associatedRow: {}, // 当前已关联的row
      /* 页面name标识集合 */
      pageNameTypeList: {
        commodityAdd: 'commodityAdd',
        waitAccess: 'waitAccess',
        batchAddSingle: 'batchAddSingle',
        batchAddMultiple: 'batchAddMultiple'
      }
    }
  },
  watch: {
    visible (val) {
      this.dialogVisible = val;
      if (!val) {
        return false;
      }
      /* nextTick解决进入弹框请求接口loading异常问题 */
      this.$nextTick(() => {
        this.handleGetTableData();
      });
    }
  },
  methods: {
    /* 操作栏按钮渲染方法 */
    renderActionBtnFunc (h, { row, index }) {
      let btnLabel = '关联';
      let calledFunc = this.handleAssociateGoods;
      if (this.tabs.current === this.tabs.nameList[1]) {
        btnLabel = '取消';
        calledFunc = this.handleCancelGoods;
      }
      return (
        <div class="table-action">
          {
            <el-button
              size="mini"
              type="text"
              onClick={() => calledFunc(row, index)}
            >{ btnLabel }
            </el-button>
          }
        </div>
      );
    },
    /* 获取查询请求URL方法 */
    getQueryRequestApiFn () {
      const requestApiList = {
        /* 商品新增 */
        [this.pageNameTypeList.commodityAdd]: {
          url: '/sysback/saletypeupdate/getProductPagerBySaleType',
          type: 'post'
        },
        /* 待准入-未完善 */
        [this.pageNameTypeList.waitAccess]: {
          url: '/sysback/saletypeupdate/getProductPagerBySaleType',
          type: 'post'
        },
        /* 批量新增 */
        [this.pageNameTypeList.batchAddSingle]: {
          url: '/sysback/saleprice/type/area/search',
          type: 'post'
        },
        /* 批量新增多计量 */
        [this.pageNameTypeList.batchAddMultiple]: {
          url: '/sysback/saleprice/type/area/search',
          type: 'post'
        },
      }
      return requestApiList[this.pageNameType];
    },
    /* 获取提交请求URL方法 */
    getSubmitRequestApiFn () {
      const requestApiList = {
        /* 商品新增 */
        [this.pageNameTypeList.commodityAdd]: {
          url: '/sysback/salepricesku/createByProductUuid',
          type: 'post'
        },
        /* 待准入-未完善 */
        [this.pageNameTypeList.waitAccess]: {
          url: '/sysback/salepricesku/createByProductUuid',
          type: 'post'
        },
        /* 批量新增 */
        [this.pageNameTypeList.batchAddSingle]: {
          url: '/sysback/salepriceskubatchadd/createByOtherProductGroup',
          type: 'post'
        },
        /* 批量新增多计量 */
        [this.pageNameTypeList.batchAddMultiple]: {
          url: '/sysback/salepriceskubatchadd/createByOtherProductGroup',
          type: 'post'
        },
      }
      return requestApiList[this.pageNameType];
    },
    /* 获取映射查询入参方法的方法 */
    getFunctionMappingQueryParamsFn () {
      const mapMethodsList = {
        /* 商品新增 */
        [this.pageNameTypeList.commodityAdd]: this.getParamsByAddFn,
        /* 待准入-未完善 */
        [this.pageNameTypeList.waitAccess]: this.getParamsByWaitFn,
        /* 批量新增 */
        [this.pageNameTypeList.batchAddSingle]: this.getParamsByBatchSingleFn,
        /* 批量新增多计量 */
        [this.pageNameTypeList.batchAddMultiple]: this.getParamsByBatchMultipleFn,
      }
      return mapMethodsList[this.pageNameType];
    },
    /* 获取默认入参方法(商品新增、待准入页面) */
    getDefaultParamsFn (spuNo, productName) {
      return [
        {
          name: 'spuNo',
          value: spuNo
        },
        {
          'name': 'spuNo_q',
          'value': 'EQ'
        },
        {
          'name': 'productName',
          'value': productName
        },
        {
          'name': 'productName_q',
          'value': 'Like'
        },
        {
          name: 'saleType',
          value: '2'
        },
        {
          name: 'isSaleMultiUnit',
          value: this.isSaleMultiUnit
        }
      ]
    },
    /* --------------------- 获取对应不同页面的查询接口入参的方法 （start） --------------------- */
    /* 商品新增 */
    getParamsByAddFn ({ spuNo, productName, associatedRowUuid }) {
      const params = this.getDefaultParamsFn(spuNo, productName);
      const uuidsList = {
        [this.tabs.nameList[0]]: {
          name: 'productUuidsNotIn',
          value: associatedRowUuid
        },
        [this.tabs.nameList[1]]: {
          name: 'productUuidsIn',
          value: associatedRowUuid
        }
      }
      const searchParams = [...params, uuidsList[this.tabs.current]];
      const data = {
        sortName: '',
        sortType: '',
        searchParam: JSON.stringify(searchParams),
      }
      return data;
    },
    /* 待准入-未完善 */
    getParamsByWaitFn ({ spuNo, productName, associatedRowUuid }) {
      const params = this.getDefaultParamsFn(spuNo, productName);
      const uuidsList = {
        [this.tabs.nameList[0]]: {
          name: 'productUuidsNotIn',
          value: associatedRowUuid
        },
        [this.tabs.nameList[1]]: {
          name: 'productUuidsIn',
          value: associatedRowUuid
        }
      }
      const searchParams = [...params, uuidsList[this.tabs.current]];
      const data = {
        sortName: '',
        sortType: '',
        searchParam: JSON.stringify(searchParams),
      }
      return data;
    },
    /* 批量新增-售价 */
    getParamsByBatchSingleFn ({ spuNo, productName, associatedRowUuid }) {
      const params = { spuNo, productName };
      const uuidsList = {
        [this.tabs.nameList[0]]: { productUuidNotInList: [associatedRowUuid] },
        [this.tabs.nameList[1]]: { productUuidInList: [associatedRowUuid] }
      }
      const data = { ...params, ...uuidsList[this.tabs.current] }
      return data;
    },
    /* 批量新增-售价多计量 */
    getParamsByBatchMultipleFn ({ spuNo, productName, associatedRowUuid }) {
      const params = { spuNo, productName };
      const uuidsList = {
        [this.tabs.nameList[0]]: { productUuidNotInList: [associatedRowUuid] },
        [this.tabs.nameList[1]]: { productUuidInList: [associatedRowUuid] }
      }
      const data = { ...params, ...uuidsList[this.tabs.current] }
      return data;
    },
    /* --------------------- 获取对应不同页面的查询接口入参的方法 （end） --------------------- */
    /* 获取查询请求入参方法 */
    getPriceGroupGoodsActionParamsFn () {
      const { spuNo, productName } = this.formData;
      const associatedRowUuid = this.associatedRow[this.uuidName];
      const getParamsFn = this.getFunctionMappingQueryParamsFn();
      const params = getParamsFn({
        spuNo,
        productName,
        associatedRowUuid
      });
      const data = {
        ...params,
        nowPage: this.pagination.pageNum,
        pageShow: this.pagination.pageSize
      }
      return data;
    },
    /* 获取表格数据事件 */
    handleGetTableData () {
      const data = this.getPriceGroupGoodsActionParamsFn();
      this.getPriceGroupGoodsAction(data).then(retData => {
        if (!retData) {
          this.tableInfo.dataSource = [];
          return false;
        }
        if (!retData.results) {
          this.tableInfo.dataSource = [];
          return false;
        }
        this.tableInfo.dataSource = retData.results;
        this.pagination.total = retData.totalNum;
      })
    },
    /* 价格组表格数据action请求 */
    getPriceGroupGoodsAction (data) {
      const { url, type } = this.getQueryRequestApiFn();
      let loading = this.$loading({ target: '.el-dialog__body' });
      return new Promise(resolve => {
        ApiRequest(url, type, data, false).then(res => {
          loading.close();
          if (!isResponseSuccess(res)) {
            resolve(false);
            return false;
          }
          resolve(res.retData);
        }).catch(() => {
          loading.close();
        })
      })
    },
    /* 切换tabs事件 */
    handleSwitchTabs () {
      this.pagination.pageNum = 1;
      if (!this.associatedRow.uuid && this.tabs.current === this.tabs.nameList[1]) {
        this.tableInfo.dataSource = [];
        this.pagination.total = 0;
        return false;
      }
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 查询方法 */
    handleQueryData () {
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 清空方法 */
    handleResetData () {
      const name = 'formData';
      this.$refs[name].resetFields();
    },
    /* 关联事件 */
    handleAssociateGoods (row, index) {
      this.associatedRow = row;
      this.$message.success('关联成功');
      this.$nextTick(() => {
        this.handleGetTableData(); // 重新加载表格数据
      })
    },
    /* 取消事件 */
    handleCancelGoods (row, index) {
      this.associatedRow = {};
      this.$message.success('取消成功');
      this.tableInfo.dataSource = [];
    },
    /* 改变页码事件 */
    handlePageChange (currentPage) {
      this.pagination.pageNum = currentPage;
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 改变当前页条数大小事件 */
    handlePageSizeChange (pageSize) {
      this.pagination.total = pageSize;
      if (this.tableInfo.dataSource.length === 0) {
        return false;
      }
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 清空状态方法 */
    clearConditionsFn () {
      this.pagination = {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页条数
        total: 0 // 总条数
      }
      this.tabs.current = this.tabs.nameList[0]; // tabs页签重置
      this.handleResetData(); // form表单内容重置
    },
    /* 取消关联事件 */
    handleCloseShowDialog () {
      this.clearConditionsFn();
      this.associatedRow = {}
      this.$emit('getExisitingPriceGroup', false)
      this.$emit('update:visible', false)
    },
    /* 确定关联事件 */
    handleSubmitPriceGroup () {
      this.clearConditionsFn();
      if (!this.associatedRow.uuid) {
        this.$emit('getExisitingPriceGroup', false)
        this.$emit('update:visible', false)
        return false;
      }
      let data = { fromProductUuid: this.associatedRow[this.uuidName] };
      if (this.productUuid) { data.sourceProductUuid = this.productUuid }
      const submitUuid = generateUuid(); // 每次二级弹框提交时重新生成
      this.createByProductUuidAction(data, submitUuid).then(retData => {
        if (!retData) {
          return false;
        }
        this.$message.success('关联成功');
        this.$emit('getSubmitUuid', submitUuid);
        this.$emit('getExisitingPriceGroup', true);
        this.$emit('update:visible', false);
      })
    },
    /* 确定关联action请求 */
    createByProductUuidAction (data, submitUuid) {
      const { url, type } = this.getSubmitRequestApiFn();
      let loading = this.$loading({ target: '.el-dialog__body' });
      return new Promise(resolve => {
        ApiRequest(`${url}?uuid=${submitUuid}`, type, data, true).then(res => {
          loading.close();
          if (res.retStatus !== '1') {
            this.$emit('getExisitingPriceGroup', false)
            resolve(false);
            return false;
          }
          resolve(true);
        }).catch(() => {
          this.$emit('getExisitingPriceGroup', false)
          loading.close();
        })
      })
    },
  }
}
</script>
<style lang="less" scoped>
/* 查询清空批量操作栏样式 */
/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
